package com.itheima.sfbx.trade.face.impl;

import com.itheima.sfbx.trade.adapter.WapPayAdapter;
import com.itheima.sfbx.framework.commons.constant.trade.TradeCacheConstant;
import com.itheima.sfbx.framework.commons.enums.trade.TradeEnum;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.trade.face.WapPayFace;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.dto.trade.TradeVO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName WapPayFaceImpl.java
 * @Description 手机网页支付Face接口实现
 */
@Slf4j
@Component
public class WapPayFaceImpl implements WapPayFace {

    @Autowired
    WapPayAdapter wapPayAdapter;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public TradeVO wapTrade(TradeVO tradeVO) {
        //1、锁对象；合同编号 或者 合同订单号
        Long productOrderNo = tradeVO.getProductOrderNo();
        //2、设置锁名称
        String lockName = TradeCacheConstant.CREATE_PAY + productOrderNo;
        //3、获取锁对象（公平锁）
        RLock lock = redissonClient.getFairLock(lockName);
        try {
            //4、尝试获取锁；锁的过期时间和单位
            if(lock.tryLock(TradeCacheConstant.REDIS_WAIT_TIME, TimeUnit.SECONDS)) {
                //5、获取锁成功，执行业务逻辑；根据交易对象获取支付表单信息
                return wapPayAdapter.wapTrade(tradeVO);
            } else {
                throw new RuntimeException("获取创建交易支付表单的分布式锁失败！");
            }
        } catch (Exception e) {
            throw new RuntimeException("获取支付表单失败！");
        } finally {
            //6、释放锁
            lock.unlock();
        }

    }
}
